<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button class="add">新增</button>
    <button class="get">获取</button>
</body>
<script>
    var add = document.getElementsByClassName("add")[0];
    var get = document.getElementsByClassName("get")[0];


    // cookie的新增:
    // 1. cookie的存取都依赖于document.cookie
    // 2. cookie是以键值对(key=value)形式存在的字符串
    // 3. cookie存储的时候是一条一条存的, 取的时候将所有cookie整合到一起返回,用"; "分隔
    // 4. cookie可以设置存储路径和过期时间


    // cookie的获取:
    // 1. cookie的存取都依赖于document.cookie
    // 2. cookie是以键值对(key=value)形式存在的字符串
    // 3. cookie存储的时候是一条一条存的, 取的时候将所有cookie整合到一起返回,用"; "分隔



    add.onclick = function () {
        var date = new Date();
        date.setSeconds(date.getSeconds() + 30 * 60);

        //  /
        document.cookie = "user=a123123; expires=" + date.toUTCString() + "; path=/";
        document.cookie = "pwd=123123; expires=" + date.toUTCString() + "; path=/";
        document.cookie = "phone=17386141517; expires=" + date.toUTCString() + "; path=/";
        document.cookie = "email=123123@qq.com; expires=" + date.toUTCString() + "; path=/";
    }

    get.onclick = function () {
        console.log(document.cookie);

        // cookie解析
        // 方法1:

        /* var cookie = document.cookie;
        var data = {};
        if (cookie) { // 有数据在解析
            var list = cookie.split("; ");
            console.log(list);

            for (var i = 0; i < list.length; i++) {
                var item = list[i]; // 'user=a123123', 'pwd=123123'
                var name = item.split("=")[0];
                var val = item.split("=")[1];
                data[name] = val;
            }
        }
        console.log(data); */


        var cookie = document.cookie;
        var data = {};

        if (cookie) {
            var reg = /(\w+)=([^;]+)/g;
            var arr = null;
            while (arr = reg.exec(cookie)) {
                // console.log(arr);
                var name = arr[1];
                var val = arr[2];
                data[name] = val;
            }
        }

        console.log(data);
    }


    // cookie封装
    // setCookie(key,value,expires,path="/")
    //  1. expires 有参数 => 设置过期时间
    //  2. expires 没有参数 => 不设置过期时间 => 浏览器关闭就过期

    // getCookie(key)  => 根据传入的键名返回键值
    // 1. 有对应键名 => 键值      getCookie("user") => "a123123"
    // 2. 没有对应键名 => ""      getCookie("hello") => ""



</script>

</html>